<template>
  <div class="bg-white rounded-lg shadow-md p-6">

    <h1 class="text-xl font-semibold text-gray-800 mb-3">个人中心</h1>

    <el-form
      ref="profileForm"
      :model="user"
      :rules="rules"
      label-position="top"
    >
      <!-- 头像上传 -->
      <div class="flex items-center mb-6">
        <el-avatar v-if="user.avatarUrl" :size="60" :src="user.avatarUrl" class="border-4">
          <img :src="user.avatarUrl" alt="" />
        </el-avatar>
        <div class="ml-6">
          <!-- 账号信息 -->
          <p class="f-13 text-gray-500 mt-2">会员等级：v1</p>
          <p class="f-13 text-gray-500 mt-2">会员编码：{{ user.id }}</p>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="mb-8">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" :disabled="!user.username.startsWith('wx-')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="user.nickname" :disabled="!!user.nickname"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12"> 
            <el-form-item label="性别" prop="sex">
              <el-select v-model="user.sex" placeholder="请选择性别">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
                <el-option label="其它" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信" prop="wechat">
              <el-input v-model="user.wechat" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="自我介绍" prop="remark">
          <el-input
            v-model="user.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入自我介绍"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存修改
        </el-button>
      </div>
      
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { userInfo,updateUser } from "./api/index.js";
import Cookies from 'js-cookie'
// 表单引用
const profileForm = ref(null);

// 状态
const saving = ref(false);

// 个人中心数据
const user = reactive({
  avatar: null,
  created_at: "",
  email: "",
  id: 0,
  login_date: "",
  phone: null,
  remark: null,
  sex: "0",
  status: null,
  username: "",
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
  remark: [{ max: 200, message: "长度不能超过 200 个字符", trigger: "blur" }],
};

// 初始化
onMounted(() => {
  getUserInfo();
});

/**
 * @description 获取用户信息
 */
const getUserInfo = async () => {
  try {
    const res = await userInfo();
    console.log(res);
    if (res.code === 200) {
      Object.assign(user, res.data);
      Cookies.set('un',res.data.username)
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

// 保存个人中心
async function handleSave() {
  try {
    await profileForm.value.validate();
    saving.value = true;
    let params = {
      id: user.id,
      phone: user.phone,
      sex: user.sex,
      remark: user.remark,
      wechat: user.wechat,
      username: user.username,
      nickname: user.nickname,
      email: user.email,
    }
    let res = await updateUser(params);
    if(res.code === 200 && res.data){
      ElMessage.success("个人中心已更新");
      getUserInfo();
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error(error.message || "保存失败，请稍后重试");
  } finally {
    saving.value = false;
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return "未知";
  try {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  } catch (error) {
    return dateString;
  }
}
</script>
